/*
 * drv_button.c
 *
 *  Created on: Oct 9, 2013
 *      Author: Omar Sevilla
 */

#include "derivative.h"
#include "stdtypedef.h"
#include "drv_button.h"
#include "app_indicator.h"


extern T_UBYTE 	rub_MenuCounter,
				rub_ExtMenuCounter,
	 	 	 	rub_ModeReg;

void init_button(void){
	/* Turn on clock to PortB module */
	SIM_SCGC5 |= SIM_SCGC5_PORTB_MASK;

	/* Set the PTB8 pin multiplexer to GPIO mode */
	PORTB_PCR8 = PORT_PCR_MUX(1);
	PORTB_PCR8 |= 0x03; //Pull-up resistor 
	
	/* Set the PTB9 pin multiplexer to GPIO mode */
	PORTB_PCR9 = PORT_PCR_MUX(1);
	PORTB_PCR9 |= 0x03; //Pull-up resistor
	

	/* Set the pins direction to input */
	GPIOB_PDDR &= ~(BUTTON1_SHIFT | BUTTON2_SHIFT);
}

void app_button1(void){
	 static T_UBYTE lub_Button1Flag = 0; 
	 
	 if(lub_Button1Flag == 0){		//If button already pressed
		 if(BUTTON1 == 0){				//If button is on
			 lub_Button1Flag = 1;	//Set flag of button pressed
		 }
	 }
	 else{
		 if(BUTTON1 == 1){				//If button is off
			 if(rub_ModeReg == NORMAL){
				 if(rub_MenuCounter < 2)	//If Menu Counter is less than 2
					 rub_MenuCounter++;		//Increase in 1
				 else							//Else
					 rub_MenuCounter = 0;	//Menu Counter equal to 0
			 }
			 else{
				 if(rub_ExtMenuCounter < 2)	//If Menu Counter is less than 2
					 rub_ExtMenuCounter++;		//Increase in 1
				 else							//Else
					 rub_ExtMenuCounter = 0;	//Menu Counter equal to 0				 
			 }
			 lub_Button1Flag = 0;
		 }
	 }
}

void app_button2(void){
	static T_UBYTE lub_Button2Flag = 0;
	
	if(lub_Button2Flag == 0){
		if(BUTTON2 == 0){
			lub_Button2Flag = 1;
		}
	}
	else{
		if(BUTTON2 == 1){
			if(rub_ModeReg == NORMAL){
				rub_ModeReg = EXTERNAL;
			}
			else{
				rub_ModeReg = NORMAL;
			}
			rub_MenuCounter = 0;
			rub_ExtMenuCounter = 0;
			lub_Button2Flag = 0;
		}
	}
}
